//
//  ChoiceInverterTypeView.m
//  RuiHeApp
//
//  Created by Yan Chen on 2025/8/7.
//

#import "ChoiceInverterTypeView.h"
#import "RHWindowTipManage.h"
#import "UIView+Extension.h"
#import "RHEndPointModel.h"
#import "ChoicePlantTypeCell.h"
#import "RHTools.h"
#import "RHPlantTypeModel.h"

@interface ChoiceInverterTypeView()<UIPickerViewDelegate,UIPickerViewDataSource>

@property (nonatomic ,strong) UIView *contentView;

@property (nonatomic ,strong) UIPickerView *pickerView;

@property (nonatomic ,strong) MASConstraint *bgViewTopConstraint;

@property (nonatomic ,strong) MASConstraint *bgViewBottomConstraint;

@property (nonatomic ,assign) NSInteger productTypeIndex;

@property (nonatomic ,assign) NSInteger devTypeIndex;

@property (nonatomic, strong) RHPlantTypeModel *curTypeModel;
@end
@implementation ChoiceInverterTypeView


-(instancetype)init
{
    if(self = [super init]){
        [self setupUI];
    }
    return self;
}
- (void)setInvTypeList:(NSArray<RHPlantTypeModel *> *)invTypeList
{
    _invTypeList = invTypeList;
 
    //默认选中第一个
    if(invTypeList.count>0){
    
        RHPlantTypeModel *productTypeModel = [invTypeList firstObject];
        if(productTypeModel.types.count>0){
            RHPlantTypeModel *devTypeModel = [productTypeModel.types firstObject];
            if (devTypeModel.types.count>0) {
                RHPlantTypeModel *invTypeModel = [devTypeModel.types firstObject];
                self.curInvType = invTypeModel.plantType;
            }
            
        }

    }
}

- (void)setupUI{
    kWeakSelf;
    [self setBackgroundColor:[UIColor.blackColor colorWithAlphaComponent:0]];
    
    UIView *touchView = [[UIView alloc] init];
    [touchView setBackgroundColor:UIColor.clearColor];
    [self addSubview:touchView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    touchView.userInteractionEnabled = YES;
    [touchView addGestureRecognizer:tap];
    
    UIView *contentView = kView;
    contentView.backgroundColor = UIColor.whiteColor;
    [self addSubview:contentView];
    self.contentView = contentView;
    
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        self.bgViewTopConstraint = make.top.equalTo(self.mas_bottom);
        
    }];
    
    _titleLab = [[QMUILabel alloc] init];
    [_titleLab setText:@"请选择".rh_localized];
    _titleLab.numberOfLines = 0;
    [_titleLab setTextAlignment:NSTextAlignmentCenter];
    [_titleLab setFont:[UIFont systemFontOfSize:16]];
    [_titleLab setTextColor:FontColor(@"#969799")];
    _titleLab.backgroundColor = UIColor.whiteColor;
    [contentView addSubview:_titleLab];
    
    QMUIButton *sureBtn = [[QMUIButton alloc]init];
    [sureBtn setTitle:@"确定".rh_localized forState:UIControlStateNormal];
    sureBtn.titleLabel.font = kSYSTEMFONT(15);
    [sureBtn setTitleColor:FontColor(@"#969799") forState:UIControlStateNormal];
    [contentView addSubview:sureBtn];
    
    //    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    //    [_tableView setSeparatorColor:FontColor(@"#F5F5F5")];
    //    [_tableView setBackgroundColor:UIColor.whiteColor];
    //    [_tableView setDelegate:self];
    //    [_tableView setDataSource:self];
    //    [_tableView registerClass:[ChoicePlantTypeCell class] forCellReuseIdentifier:@"ChoicePlantTypeCell"];
    //    [contentView addSubview:_tableView];
    
    _pickerView = [[UIPickerView alloc]init];
    _pickerView.delegate = self;
    _pickerView.dataSource = self;
    [contentView addSubview:_pickerView];
    
    UIView *lineV = [[UIView alloc] init];
    [lineV setBackgroundColor:FontColor(@"#eeeeee")];
    [contentView addSubview:lineV];
    
    UIView *btnView = kView;
    btnView.backgroundColor = UIColor.whiteColor;
    [contentView addSubview:btnView];
    [btnView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_offset(0);
    }];
    
    QMUIButton *cancelBtn = [[QMUIButton alloc]init];
    [cancelBtn setTitle:@"取消".rh_localized forState:UIControlStateNormal];
    [cancelBtn setTitleColor:kCOLOR_HEX(@"646566") forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = kSYSTEMFONT(16);
    [btnView addSubview:cancelBtn];
    CGFloat bottom_margin = 0;
    if(kSafe_bottom == 0){
        bottom_margin = 10;
    }
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_offset(0);
        make.height.offset(kScaleW(45));
        make.bottom.offset(-bottom_margin-kSafe_bottom);
    }];
    
    UIView *marginView = kView;
    marginView.backgroundColor = CFTabViewBgColor;
    [contentView addSubview:marginView];
    [marginView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.height.offset(10);
        make.bottom.equalTo(btnView.mas_top);
    }];
    
    
    [touchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    
    
    CGFloat btnWidth =  [sureBtn.titleLabel.text getStringWidthFont:sureBtn.titleLabel.font limitHeight:20];
    CGFloat titleWidth = (kUI_WINDOW_W - (30 + btnWidth)*2);
    
    [_titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_offset(0);
        make.height.mas_equalTo(49);
        make.top.mas_offset(0);
        make.width.offset(titleWidth);
    }];
    
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf.titleLab);
        make.right.mas_offset(-15);
        make.height.offset(40);
    }];
    
    [lineV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(1);
        make.top.equalTo(weakSelf.titleLab.mas_bottom);
    }];
    
    //    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.top.equalTo(weakSelf.titleLab.mas_bottom);
    //        make.left.right.mas_offset(0);
    //        make.bottom.equalTo(marginView.mas_top);
    //        make.height.offset(45*self.plantTypeList.count);
    //    }];
    
    [_pickerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.titleLab.mas_bottom);
        make.left.right.mas_offset(0);
        make.bottom.equalTo(marginView.mas_top);
        make.height.offset(45*4);
    }];
    
    contentView.layer.cornerRadius = 8;
    contentView.layer.maskedCorners = kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner;
    
    [tap.rac_gestureSignal subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
        if (weakSelf.choiceResultBlock) {
            weakSelf.choiceResultBlock(nil);
        }
        [weakSelf hidden];
    }];
    
    [[cancelBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf hidden];
    }];
    
    [[sureBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        
        if(weakSelf.curInvType){
            if (weakSelf.choiceResultBlock) {
                weakSelf.choiceResultBlock(weakSelf.curTypeModel);
            }
            [weakSelf hidden];
        }
    }];
    
    
}



- (void)setCurInvType:(NSString *)curType
{
    _curInvType = curType;
    kWeakSelf;
    [self.invTypeList enumerateObjectsUsingBlock:^(RHPlantTypeModel * _Nonnull typeModel, NSUInteger typeIdx, BOOL * _Nonnull stop) {
        [typeModel.types enumerateObjectsUsingBlock:^(RHPlantTypeModel*  _Nonnull subType, NSUInteger idx, BOOL * _Nonnull stop) {
            if([subType.plantType isEqualToString:weakSelf.curInvType]){
                weakSelf.curTypeModel = subType;
            }
        }];
    }];

}

//首次进入的时候滚动到当前值所在列
-(void)scorllToCurrentValue
{
    
    __block  NSInteger product_idx = 0;
    __block  NSInteger dev_idx = 0;
    __block  NSInteger inv_idx = 0;
    
    [self.invTypeList enumerateObjectsUsingBlock:^(RHPlantTypeModel * _Nonnull productTypeModel, NSUInteger productIdx, BOOL * _Nonnull stop) {
        [productTypeModel.types enumerateObjectsUsingBlock:^(RHPlantTypeModel*  _Nonnull devTypeModel, NSUInteger devIdx, BOOL * _Nonnull stop) {
            [devTypeModel.types enumerateObjectsUsingBlock:^(RHPlantTypeModel*  _Nonnull invTypeModel, NSUInteger invIdx, BOOL * _Nonnull stop) {
                if([invTypeModel.plantType isEqualToString:_curInvType]){
                    product_idx = productIdx;
                    dev_idx = devIdx;
                    inv_idx = invIdx;
                }
            }];
            
        }];
    }];

    if (self.pickerView) {
        if (product_idx < self.invTypeList.count) {
            RHPlantTypeModel *productTypeModel = self.invTypeList[product_idx];
            if (dev_idx < productTypeModel.types.count) {
                RHPlantTypeModel *devTypeModel = productTypeModel.types[dev_idx];
                if (inv_idx < devTypeModel.types.count) {
                    [self.pickerView selectRow:product_idx inComponent:0 animated:YES];
                    [self pickerView:self.pickerView didSelectRow:product_idx inComponent:0];
                    
                    [self.pickerView selectRow:dev_idx inComponent:1 animated:YES];
                    [self pickerView:self.pickerView didSelectRow:dev_idx inComponent:1];
                    
                    [self.pickerView selectRow:inv_idx inComponent:2 animated:YES];
                    [self pickerView:self.pickerView didSelectRow:inv_idx inComponent:2];
                }
                
                
            }
        }
    }

}

- (void)hidden{
    kWeakSelf;
    [self.bgViewBottomConstraint uninstall];
    [self.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
        self.bgViewTopConstraint = make.top.equalTo(self.mas_bottom);
        
    }];
    [UIView animateWithDuration:0.2 animations:^{
        [self setNeedsLayout];
        [self layoutIfNeeded];
        [self setBackgroundColor:[UIColor.blackColor colorWithAlphaComponent:0]];
    } completion:^(BOOL finished) {
        
        [self removeFromSuperview];
        
    }];
}


- (void)showAnimation{
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    self.frame = [UIApplication sharedApplication].keyWindow.bounds;
    
    [self setNeedsLayout];
    [self layoutIfNeeded];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.bgViewTopConstraint uninstall];
        [self.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
            self.bgViewBottomConstraint = make.bottom.mas_offset(0);
            
        }];
        [UIView animateWithDuration:0.2 animations:^{
            [self setNeedsLayout];
            [self layoutIfNeeded];
            [self setBackgroundColor:[UIColor.blackColor colorWithAlphaComponent:0.3]];
        }];
    });
    
}



- (void)hiddenAnimation{
    
    
}



#pragma mark ------ pickView delegate
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 40;
}

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
  
    if(component == 0){
        return self.invTypeList.count;
    }else  if(component == 1){
        if(self.invTypeList.count>0){
            RHPlantTypeModel *productTypeModel =  self.invTypeList[self.productTypeIndex];
            return productTypeModel.types.count;
        }
        
    }else{
        if(self.invTypeList.count>0){
            RHPlantTypeModel *productTypeModel =  self.invTypeList[self.productTypeIndex];
            RHPlantTypeModel *devTypeModel = productTypeModel.types[self.devTypeIndex];
            return devTypeModel.types.count;
        }
    }
    return 0;
}

- (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString *content = @"";
    if(component == 0 ){
        RHPlantTypeModel *typeModel =  self.invTypeList[row];
//        content = [RHTools changeDevType:typeModel.plantType];
        content = typeModel.plantTypeName;
    }else if(component == 1 ){
        if(self.invTypeList.count>0){
            RHPlantTypeModel *productTypeModel = self.invTypeList[self.productTypeIndex];
            RHPlantTypeModel *devTypeModel = productTypeModel.types[row];
            content = devTypeModel.plantTypeName;
        }
    }else{
        if(self.invTypeList.count>0){
            RHPlantTypeModel *productTypeModel = self.invTypeList[self.productTypeIndex];
            RHPlantTypeModel *devTypeModel = productTypeModel.types[self.devTypeIndex];
            RHPlantTypeModel *invTypeModel = devTypeModel.types[row];
            content = invTypeModel.plantTypeName;
        }
    }
    
    return content;
}


- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel) {
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.font = [UIFont systemFontOfSize:14];
        pickerLabel.textAlignment = NSTextAlignmentCenter;
        pickerLabel.numberOfLines = 2;
        //        pickerLabel.textColor = [UIColor blueColor];
    }
    pickerLabel.text = [self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}



- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{

    if(component == 0){
        self.productTypeIndex = row;
        self.devTypeIndex = 0;
        [pickerView reloadComponent:1];
        [pickerView reloadComponent:2];
        
        RHPlantTypeModel *productTypemodel = self.invTypeList[row];
        RHPlantTypeModel *devTypeModel = [productTypemodel.types firstObject];
        RHPlantTypeModel *invTypeModel = [devTypeModel.types firstObject];
        self.curInvType = invTypeModel.plantType;
        self.curTypeModel = invTypeModel;
        NSLog(@"---->选择了第 1 列");
        [self.pickerView selectRow:0 inComponent:1 animated:NO];
    }else if(component == 1){
        self.devTypeIndex = row;
        [pickerView reloadComponent:2];
        
        RHPlantTypeModel *productTypemodel = self.invTypeList[self.productTypeIndex];
        RHPlantTypeModel *devTypeModel = productTypemodel.types[row];
        RHPlantTypeModel *invTypeModel = [devTypeModel.types firstObject];
        self.curInvType = invTypeModel.plantType;
        self.curTypeModel = invTypeModel;
        NSLog(@"---->选择了第 2 列");
    }else{
        RHPlantTypeModel *productTypemodel = self.invTypeList[self.productTypeIndex];
        RHPlantTypeModel *devTypeModel = productTypemodel.types[self.devTypeIndex];
        RHPlantTypeModel *invTypeModel = devTypeModel.types[row];
        self.curInvType = invTypeModel.plantType;
        self.curTypeModel = invTypeModel;
        NSLog(@"---->选择了第 3 列");
    }
}

-(void)dealloc{
    NSLog(@"---->ChoiceInverterTypeView dealloc");
}

@end
